using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.ComponentModel;
using System.Collections.Generic;


public struct Vote
{
	private string m_userName;
	private bool m_answer;
	
	public string UserName {
		get { return this.m_userName; }
		set { this.m_userName = value; }
	}

	public bool Answer {
		get { return this.m_answer; }
		set { this.m_answer = value; }
	}

	public Vote(string userName, bool vote)
	{
		this.m_userName = userName;
		this.m_answer = vote;
	}
}

[DataObject]
public class PollService : BasicService<List<Vote>>
{
	[DataObjectMethod(DataObjectMethodType.Insert)]
	public void Insert(Guid id, Vote newVote)
	{
		if (string.IsNullOrEmpty(newVote.UserName)) {
			return;
		}
		
		List<Vote> _poll = this[id];
		Vote _existingVote = _poll.Find(
			new Predicate<Vote>(
					delegate(Vote vote)
					{
						return vote.UserName == newVote.UserName;
					}));
		
		if (!string.IsNullOrEmpty(_existingVote.UserName)) {
			_poll.Remove(_existingVote);
			_existingVote.Answer = newVote.Answer;
			_poll.Add(_existingVote);
		} else {
			_poll.Add(newVote);
		}
	}

	[DataObjectMethod(DataObjectMethodType.Update)]
	public void Update(Guid id, Vote vote)
	{
		if (string.IsNullOrEmpty(vote.UserName)) {
			return;
		}
		
		List<Vote> _poll = this[id];
		Vote _existingVote = _poll.Find(
			new Predicate<Vote>(
					delegate(Vote _vote)
					{
						return _vote.UserName == vote.UserName;
					}));
		
		if (!string.IsNullOrEmpty(_existingVote.UserName)) {
			_existingVote.Answer = vote.Answer;
		}
	}
	
	[DataObjectMethod(DataObjectMethodType.Select)]
	public List<Vote> Select(Guid id)
	{
		return this[id];
	}

	[DataObjectMethod(DataObjectMethodType.Delete)]
	public void Clear(Guid id)
	{
		this[id].Clear();
	}

	static ItemVector<String> m_pollQuestion = new ItemVector<string>();
	
	#region Interface logic
	public void AddVote(Guid id, bool vote)
	{
		this.Insert(id, new Vote(Environment.CurrentUserName, vote));
	}
	
	public ItemVector<String> Question {
		get {
			return m_pollQuestion;
		}
	}

	public bool IsActive(Guid id)
	{
		return !string.IsNullOrEmpty(this.Question[id]);
	}
	
	#endregion Interface logic
}
